package com.pubinfo.passbook.common.exception;

import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@Slf4j
@RestControllerAdvice
public class MyGlobalExceptionHandler {

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("方法参数校验:" + e.getMessage(), e);
        return JsonResult.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public JsonResult handleValidationException(ValidationException e) {
        log.error("ValidationException:", e);
        return JsonResult.error(e.getCause().getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public JsonResult handleServiceException(ServiceException e, HttpServletResponse resp) {
        log.error("ServiceException:", e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return JsonResult.error(e.getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        log.error("ValidationException:" + e.getMessage(), e);
        return JsonResult.error(e.getMessage());
    }

}